package org.dropme.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.dropme.model.Litter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.util.Log;

public class LitterDao {

	private HttpClient client;
	private final String dropPath = "http://dropme-android.appspot.com/drop"; 
	private final String pickPath = "http://dropme-android.appspot.com/pick"; 
//	private HttpHost dropHost = new HttpHost(
//			"http://dropme-android.appspot.com/drop");
//	private HttpHost pickHost = new HttpHost(
//			"http://dropme-android.appspot.com/pick");

	/**
	 * 
	 * Reads the relevant {@link Litter} instances. Returns null if there is a
	 * problem.
	 * 
	 * @param latitude
	 * @param longitude
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws JSONException
	 * @throws URISyntaxException 
	 */
	public List<Litter> read(Double latitude, Double longitude)
			throws ClientProtocolException, IOException, JSONException, URISyntaxException {
		if (client == null) {
			client = new DefaultHttpClient();
		}
		HttpGet request = new HttpGet();
		request.setURI(new URI(pickPath));
		HttpParams params = new BasicHttpParams();
		params.setDoubleParameter("latitude", latitude);
		params.setDoubleParameter("longitude", longitude);
		request.setParams(params);
		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() < 300) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			StringBuilder builder = new StringBuilder();
			for (String line = null; (line = reader.readLine()) != null;) {
				builder.append(line).append("\n");
			}
			JSONTokener tokener = new JSONTokener(builder.toString());
			JSONObject results = new JSONObject(tokener);
			if(results.has("results")) {
				JSONArray array = results.getJSONArray("results");
				List<Litter> litters = new ArrayList<Litter>();
				for (int i = 0; i < array.length(); i++) {
					litters.add(Litter.fromJSON(array.getJSONObject(i)));
				}
				return litters;
			}
		}
		return null;
	}

	/**
	 * 
	 * Writes a Litter into the service. It returns true if the write is
	 * successful. False otherwise
	 * 
	 * @param litter
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws URISyntaxException 
	 */
	public boolean write(Litter litter) throws ClientProtocolException,
			IOException, URISyntaxException {
		if (client == null) {
			client = new DefaultHttpClient();
		}
		
		HttpGet request = new HttpGet();
		request.setURI(new URI(dropPath));
		HttpParams params = litter.attach(new BasicHttpParams());
		request.setParams(params);
		HttpResponse response = client.execute(request);
		String content = convertStreamToString(response.getEntity().getContent());
		return response.getStatusLine().getStatusCode() < 300;
	}
	
	  public String convertStreamToString(InputStream is) throws IOException {
	        Log.e("meh", "convertStreamToString()");
	        if (is != null) {
	            StringBuilder sb = new StringBuilder();
	            String line;

	            try {
	                BufferedReader reader = new BufferedReader(
	                        new InputStreamReader(is, "UTF-8"));
	                while ((line = reader.readLine()) != null) {
	                    sb.append(line).append("\n");
	                }
	            } finally {
	                is.close();
	            }
	            return sb.toString();
	        } else {
	            Log.e("meh", "Error obtaining data!!!");
	            return "";
	        }
	    }

}
